﻿using System;
using System.Collections.Generic;
using System.Linq;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Entities;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Atmk.WaterMeter.MIS.Entities.Models;
using Newtonsoft.Json;

namespace Atmk.WaterMeter.MIS.Logic
{
    /// <summary>
    /// 系统参数配置
    /// </summary>
    public class SystemParamentsLogic : ISystemParamentsLogic
    {
        private static readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();

        private readonly IRepository _repository;
        private readonly IProjectConfigurationRepository _projectConfigurationRepository;
        private ProjectConfigurationModel _projectConfigurationModel;

        public SystemParamentsLogic(
            IRepository repository,
            IProjectConfigurationRepository projectConfigurationRepository
        )
        {
            _projectConfigurationRepository = projectConfigurationRepository;
            _repository = repository;
        }

        /// <summary>
        /// 将配置读取并赋值给_projectConfigurationModel
        /// </summary>
        /// <param name="projectId"></param>
        private void ReadConfigurationToModel(string projectId)
        {
            ParameterList config = _projectConfigurationRepository.GetConfiguration(projectId);
            try
            {
                _projectConfigurationModel = string.IsNullOrEmpty(config.Config)
                    ? new ProjectConfigurationModel()
                    : JsonConvert.DeserializeObject<ProjectConfigurationModel>(config.Config);
            }
            catch (Exception e)
            {
                _logger.Error(e);
                _projectConfigurationModel = new ProjectConfigurationModel();
            }
        }

        private bool SaveChangeConfiguration(string projectId)
        {
            var jsonConfig = JsonConvert.SerializeObject(_projectConfigurationModel);
            int result = _projectConfigurationRepository.UpdateConfig(projectId, jsonConfig);
            return result > 0;
        }


        /// <summary>
        /// 获取水表类型集合
        /// </summary>
        /// <returns></returns>
        public List<string> MeterTypeGet(string projectId)
        {
            try
            {
                ReadConfigurationToModel(projectId);
                //获取字段
                var meterType = JsonConvert.DeserializeObject<List<string>>(_projectConfigurationModel.meterType);
                return meterType;
            }
            catch (Exception e)
            {
                _logger.Error(e);
                throw new Exception(e.Message, e);
            }
        }

        /// <summary>
        /// 获取初始参数
        /// </summary>
        /// <returns></returns>
        public object InitialParamentSelect(string projectId)
        {
            ReadConfigurationToModel(projectId);
            //获取字段
            var payType = JsonConvert.DeserializeObject<List<string>>(_projectConfigurationModel.payType??string.Empty);
            var meterType = JsonConvert.DeserializeObject<List<string>>(_projectConfigurationModel.meterType ?? string.Empty);
            if (payType == null)
                payType = new List<string>();
            if (meterType == null)
                meterType = new List<string>();
            //获取信息
            var result = new
            {
                communicationType = 1, //集中器通讯方式：固定IP与非固定IP，二者只传一个.0或1
                payType, //缴费方式（后付费，预付费，账户预存），多选
                meterType //表类型（冷水水表、生活热水水表、直饮水水表、中水水表、FS型大水表），多选
            };
            return result;
        }

        /// <summary>
        /// 修改初始参数
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="obj"></param>
        /// <param name="warn"></param>
        /// <returns></returns>
        public bool InitialParamentUpdate(string projectId, dynamic obj, out string warn)
        {
            try
            {
                warn = string.Empty;
                ReadConfigurationToModel(projectId);
                _projectConfigurationModel.payType = obj.payType.ToString();
                _projectConfigurationModel.meterType = obj.meterType.ToString();
                return SaveChangeConfiguration(projectId);
            }
            catch (Exception e)
            {
                _logger.Error(e);
                warn = e.Message;
                return false;
            }
        }

        /// <summary>
        /// 获取初始参数
        /// </summary>
        /// <returns></returns>
        public object SystemParamentSelect(string projectId)
        {
            //获取字段
            ReadConfigurationToModel(projectId);

            //获取信息
            var basicInfo = new
            {
                //基础信息
                company = _projectConfigurationModel.company, //单位名称
                backupPath = _projectConfigurationModel.backupPath, //备份路径
                autoBackup = Simple.IntConvertString(_projectConfigurationModel.autoBackup), //退出时自动备份，0或1
                keepDays = Simple.IntConvertString(_projectConfigurationModel.keepDays), //自动备份文件保留天数
                usage = Simple.IntConvertString(_projectConfigurationModel.usage), //出厂用量
                decimalLength = Simple.IntConvertString(_projectConfigurationModel.decimalLength) //小数位数
            };
            var invoice = new
            {
                //发票信息
                numberCreate = _projectConfigurationModel.invoiceNumberCreate, //票据编号生成方式：自动生成，手工输入.0或1
                numberPrefix = _projectConfigurationModel.invoiceNumberPrefix, //票据编号前缀
                numberLength = Simple.IntConvertString(_projectConfigurationModel.invoiceNumberLength), //票据编号长度
                currentNumber = _projectConfigurationModel.invoiceCurrentNumber, //当前票据编号
                settingTips = _projectConfigurationModel.invoiceSettingTips //票据编号设置说明,可以是富文本文字
            };
            var userCode = new
            {
                //用户编号
                numberCreate = _projectConfigurationModel.userNumberCreate, //用户编号生成方式：自动生成，手工输入
                numberPrefix = _projectConfigurationModel.userNumberPrefix, //用户编号前缀
                useDistrictCode = Simple.IntConvertString(_projectConfigurationModel.userDistrictCode), //使用片区编码
                numberLength = Simple.IntConvertString(_projectConfigurationModel.userNumberLength), //用户编号长度
                currentNumber = _projectConfigurationModel.userCurrentNumber, //当前用户编号
                settingTips = _projectConfigurationModel.userSettingTips //用户编号设置说明,可以是富文本文字
            };
            var dataCollect = new
            {
                //数据采集
                serviceIP = _projectConfigurationModel.serviceIP, //数据采集服务器IP
                port = Simple.IntConvertString(_projectConfigurationModel.port), //端口
                controlCount = Simple.IntConvertString(_projectConfigurationModel.controlCount), //连续控阀次数
                autoClose = Simple.IntConvertString(_projectConfigurationModel.autoClose), //欠费自动关阀,0或1
                limitValue = Simple.IntConvertString(_projectConfigurationModel.limitValue) //欠费关阀限定值
            };
            var result = new
            {
                basicInfo,
                invoice,
                userCode,
                dataCollect
            };
            return result;
        }

        /// <summary>
        /// 修改初始参数
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="obj"></param>
        /// <param name="warn"></param>
        /// <returns></returns>
        public bool SystemParamentUpdate(string projectId, dynamic obj, out string warn)
        {
            warn = string.Empty;
            try
            {
                //获取字段
                ReadConfigurationToModel(projectId);
                var basicInfo = obj.basicInfo;
                _projectConfigurationModel.company=basicInfo.company.ToString();
                _projectConfigurationModel.backupPath= basicInfo.backupPath.ToString();
                _projectConfigurationModel.autoBackup= basicInfo.autoBackup.ToString();
               _projectConfigurationModel.keepDays=basicInfo.keepDays.ToString();
                _projectConfigurationModel.usage= basicInfo.usage.ToString();
                _projectConfigurationModel.decimalLength= basicInfo.decimalLength.ToString();
                var invoice = obj.invoice;
                _projectConfigurationModel.invoiceNumberCreate =invoice.numberCreate.ToString();
                _projectConfigurationModel.invoiceNumberPrefix =invoice.numberPrefix.ToString();
                _projectConfigurationModel.invoiceNumberLength =invoice.numberLength.ToString();
                _projectConfigurationModel.invoiceCurrentNumber =invoice.currentNumber.ToString();
                _projectConfigurationModel.invoiceSettingTips =invoice.settingTips.ToString();
                var userCode = obj.userCode;
                _projectConfigurationModel.userNumberCreate =userCode.numberCreate.ToString();
                _projectConfigurationModel.userNumberPrefix =userCode.numberPrefix.ToString();
                _projectConfigurationModel.userDistrictCode =userCode.useDistrictCode.ToString();
                _projectConfigurationModel.userNumberLength =userCode.numberLength.ToString();
                _projectConfigurationModel.userCurrentNumber =userCode.currentNumber.ToString();
                _projectConfigurationModel.userSettingTips =userCode.settingTips.ToString();
                var dataCollect = obj.dataCollect;
                _projectConfigurationModel.serviceIP =dataCollect.serviceIP.ToString();
                _projectConfigurationModel.port =dataCollect.port.ToString();
                _projectConfigurationModel.controlCount =dataCollect.controlCount.ToString();
                _projectConfigurationModel.autoClose =dataCollect.autoClose.ToString();
                _projectConfigurationModel.limitValue =dataCollect.limitValue.ToString();

                return SaveChangeConfiguration(projectId);
            }
            catch (Exception e)
            {
                _logger.Error(e);
                warn = e.Message;
                return false;
            }
        }

        /// <summary>
        /// 获取基础项目信息
        /// </summary>
        /// <returns></returns>
        public object SysBaseDataSelect()
        {
            //TODO: remove
            //获取项目
            //var param = Enumerable.ToList<ProjectConfiguration>(_repository
            //    .FindAll<ProjectConfiguration>());
            //var value = ParamentValueGet("Category", param);
            //if (value.Trim().Length == 0)
            //{
            //   
            //    ParamentValueSet("Category", value, param);
            //}
            var value = "['物业费类型','证件类型','价格单位']";
            //获取信息集合
            var datas = Enumerable.ToList<SystemConfiguration>(_repository.FindAll<SystemConfiguration>());
            //赋值
            var dataList = new object[datas.Count()];
            for (var i = 0; i < datas.Count(); i++)
            {
                dataList[i] = new
                {
                    id = datas[i].Id.ToString(),
                    cateType = "", //datas[i].Category,
                    dataName = datas[i].Name,
                    addData = datas[i].Memo
                };
            }
            var result = new
            {
                cateList = JsonConvert.DeserializeObject(value),
                dataList
            };
            return result;
        }

        /// <summary>
        /// 获取基础项目信息
        /// </summary>
        /// <returns></returns>
        public object SysBaseDataSelect(string name)
        {
            //TODO: remove
            //获取信息集合
            //var datas = Enumerable
            //    .Where<SystemConfiguration>(_repository.FindAll<SystemConfiguration>(), d => d.Category == name)
            //    .ToList();
            ////赋值
            //var dataList = new object[datas.Count()];
            //for (var i = 0; i < datas.Count(); i++)
            //{
            //    dataList[i] = new
            //    {
            //        id = datas[i].Id.ToString(),
            //        cateType = /datas[i].Category,
            //        dataName = datas[i].Name,
            //        addData = datas[i].Memo
            //    };
            //}
            //var result = new
            //{
            //    dataList
            //};
            //return result;
            return null;
        }

        /// <summary>
        /// 添加基础项目信息
        /// </summary>
        /// <param name="role"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public bool AddSysBaseData(dynamic obj, out Exception exception)
        {
            //TODO: remove
            exception = null;
            try
            {
                var name = obj.dataName.ToString();

                var dataList = Enumerable.ToList<SystemConfiguration>(_repository.FindAll<SystemConfiguration>());
                if (dataList.Any(r => r.Name == name))
                {
                    exception = new Exception("项目名称重复");
                    return false;
                }
                var data = new SystemConfiguration(name)
                {
                    //Category = obj.cateType.ToString(),
                    Memo = obj.addData.ToString()
                };
                if (_repository.Add(data) > 0)
                    return true;
                exception = new Exception("添加失败");
                return false;
            }
            catch (Exception e)
            {
                _logger.Error(e);
                exception = e;
                return false;
            }
        }

        /// <summary>
        /// 修改基础项目信息
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public bool UpdateSysBaseData(dynamic obj, out Exception exception)
        {
            //TODO: remove
            try
            {
                exception = null;
                var datas = Enumerable.Where<SystemConfiguration>(_repository.FindAll<SystemConfiguration>(),
                    p => p.Id.ToString() == obj.id.ToString()).ToList();
                if (!datas.Any())
                {
                    exception = new Exception("项目信息不存在，无法修改");
                    return false;
                }
                var data = datas.First();
                data.Name = obj.dataName.ToString();
                //data.Category = obj.cateType.ToString();
                data.Memo = obj.addData.ToString();
                if (_repository.Update(data) > 0)
                    return true;
                exception = new Exception("修改失败");
                return false;
            }
            catch (Exception e)
            {
                _logger.Error(e);
                exception = e;
                return false;
            }
        }

        /// <summary>
        /// 删除基础项目信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public bool DeleteBaseData(string id, out Exception exception)
        {
            try
            {
                exception = null;
                if (Enumerable.Count<SystemConfiguration>(_repository.FindAll<SystemConfiguration>(),
                        r => r.Id.ToString() == id) == 0)
                {
                    exception = new Exception("没有费用信息");
                    return false;
                }
                var data = Enumerable.First<SystemConfiguration>(_repository
                    .FindAll<SystemConfiguration>(), r => r.Id.ToString() == id);

                if (_repository.Remove(data) > 0)
                    return true;
                exception = new Exception("删除失败");
                return false;
            }
            catch (Exception e)
            {
                _logger.Error(e);
                exception = e;
                return false;
            }
        }
    }
}